new Vue({
    el: '#app',
    data() {
        return {
            fileList: [],
            tableData: [],
            form: {
                page: 1,
                limit: 15,
            },
            loading: false,
            success: 0,
            error: 0,
            Activity: [],//活动
        }
    },
    mixins:[importMixin],
    mounted() {
        this.getData();
    },
    methods: {
        getData() {
            const that = this;
            $.ajax({
                headers: requestHeaders(),
                url: `${BASE_URL2}/generalBusiness/generalQueryByTableName`,
                type: 'POST',
                data: {
                    Data: 'business_activity',
                    Condition: "Row_Status <> '1'",
                },
                success: function (res) {
                    that.Activity = res;
                },
                complete: function (XMLHttpRequest) {
                    that.loading = false
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json"
            });
        },
        submitUpload(i = 0) {
            const that = this;
            if (i < this.tableData.length) {
                this.loading = true;
                if (this.tableData[i].isError) {
                    this.error++;
                    this.submitUpload(i + 1);
                } else if (!(!isNaN(parseFloat(this.tableData[i].Points)) && isFinite(this.tableData[i].Points))) {
                    this.tableData[i].isStatus = '2';
                    this.tableData[i].Cause = '变动积分值不是一个数字';
                    this.error++;
                    this.submitUpload(i + 1);
                } else if (this.tableData[i].Points == 0) {
                    this.tableData[i].isStatus = '2';
                    this.tableData[i].Cause = '变动积分值不能为0';
                    this.error++;
                    this.submitUpload(i + 1);
                } else if (!this.tableData[i].Notes.length > 100) {
                    this.tableData[i].isStatus = '2';
                    this.tableData[i].Cause = '备注最大长度100,当前长度' + this.tableData[i].Notes.length;
                    this.error++;
                    this.submitUpload(i + 1);
                } else { //校验通过
                    $.ajax({//查询账户信息
                        headers: requestHeaders(),
                        url: `${BASE_URL2}/member/getMemberPoint`,
                        type: 'POST',
                        data: {
                            Data: JSON.stringify([{
                                tableName: 'business_member_account_info',
                                Condition: window.btoa(unescape(encodeURIComponent("Open_ID='" + that.tableData[i].Open_ID + "'"))),
                            }, {
                                tableName: 'business_member_cash_points',
                                Condition: window.btoa(unescape(encodeURIComponent("Member_SerialNumber='" + that.tableData[i].Member_SerialNumber
                                    + "' AND Activity_SerialNumber='" + that.tableData[i].Activity_SerialNumber + "'"))),
                            }]),
                        },
                        success: function (res) {
                            let business_member_cash_points = res.business_member_cash_points,
                                business_member_account_info = res.business_member_account_info,
                                Member_SerialNumber = that.tableData[i].Member_SerialNumber,
                                Activity_SerialNumber = that.tableData[i].Activity_SerialNumber,
                                Points = that.tableData[i].Points, is = false;

                            //用户是否首次参加该活动
                            if (business_member_cash_points.length == 0) {
                                business_member_cash_points.push({
                                    Member_Points_SerialNumber: '',
                                    Member_SerialNumber,
                                    Activity_SerialNumber,
                                    Total_Points: 0,
                                    Remain_Points: 0,
                                    Sales_Points: 0,
                                })
                                is = true;//是否首次参加活动
                            }

                            //生成积分修改日志
                            let business_member_points_log = [{
                                Log_SerialNumber: '',
                                ...that.tableData[i],
                                Points_Type: '',//收入支出
                                Remain_Points: '',//剩余积分
                                Points_Title: '',
                            }]

                            //1.判断变动积分值是正还是负数
                            if (parseFloat(Points) > 0) {//增加积分
                                business_member_cash_points[0].Total_Points = accAdd(parseFloat(business_member_cash_points[0].Total_Points), parseFloat(Points));
                                business_member_cash_points[0].Remain_Points = accAdd(parseFloat(business_member_cash_points[0].Remain_Points), parseFloat(Points));
                                if (business_member_account_info.length == 1) {
                                    business_member_account_info[0].Cash_Point = accAdd(parseFloat(business_member_account_info[0].Cash_Point), parseFloat(Points));
                                    business_member_account_info[0].Cash_Point_Balance = accAdd(parseFloat(business_member_account_info[0].Cash_Point_Balance), parseFloat(Points));
                                }
                                business_member_points_log[0].Points_Type = 'Cash';//收入
                                business_member_points_log[0].Remain_Points = business_member_cash_points[0].Remain_Points;
                                business_member_points_log[0].Points_Title = that.tableData[i].Points_Title;
                            } else {//扣减积分
                                business_member_cash_points[0].Remain_Points = accAdd(parseFloat(business_member_cash_points[0].Remain_Points), parseFloat(Points));
                                business_member_cash_points[0].Sales_Points = accSub(parseFloat(business_member_cash_points[0].Sales_Points), parseFloat(Points));
                                if (business_member_account_info.length == 1) {
                                    business_member_account_info[0].Cash_Point_Balance = accAdd(parseFloat(business_member_account_info[0].Cash_Point_Balance), parseFloat(Points));
                                    business_member_account_info[0].Cash_Point_Sales = accSub(parseFloat(business_member_account_info[0].Cash_Point_Sales), parseFloat(Points));
                                }
                                business_member_points_log[0].Points_Type = 'Cash';//扣减
                                business_member_points_log[0].Remain_Points = business_member_cash_points[0].Remain_Points;
                                business_member_points_log[0].Points_Title = that.tableData[i].Points_Title;
                            }
                            if (business_member_points_log[0].Remain_Points < 0) {//积分剩余不足无法扣减
                                that.tableData[i].isStatus = '2';
                                that.tableData[i].Cause = '该用户剩余积分不足，无法扣减'
                                that.error++;
                                that.submitUpload(i + 1);
                            } else {
                                let data = {};
                                if (is) {//判断是否首次参与活动
                                    if (business_member_account_info.length == 1) {
                                        data = {
                                            Data: JSON.stringify({
                                                Add: { business_member_points_log, business_member_cash_points },
                                                Modify: { business_member_account_info }
                                            })
                                        }
                                    } else {
                                        data = {
                                            Data: JSON.stringify({
                                                Add: { business_member_points_log, business_member_cash_points },
                                            })
                                        }
                                    }
                                } else {
                                    if (business_member_account_info.length == 1) {
                                        data = {
                                            Data: JSON.stringify({
                                                Add: { business_member_points_log },
                                                Modify: { business_member_account_info, business_member_cash_points }
                                            })
                                        }
                                    } else {
                                        data = {
                                            Data: JSON.stringify({
                                                Add: { business_member_points_log },
                                                Modify: { business_member_cash_points }
                                            })
                                        }
                                    }
                                }
                                that.submitForm(data, (res) => {//提交
                                    if (res.Status == 'success') {
                                        that.tableData[i].isStatus = '1';
                                        that.tableData[i].Cause = '',
                                            that.success++;
                                    } else {
                                        that.tableData[i].isStatus = '2';
                                        that.tableData[i].Cause = '未知错误'
                                        that.error++;
                                    }
                                    that.submitUpload(i + 1);
                                })
                            }
                        },
                        complete: function (XMLHttpRequest) {
                            requestPretreatment(XMLHttpRequest);//config/config.js 响应预检
                        },
                        dataType: "json"
                    });
                }
            } else if (i != 0) {
                this.loading = false;
                this.$message.success("批量导入结束")
            } else {
                this.$message({
                    message: '请先导入模板后再上传',
                    type: 'warning'
                })
            }
        },
        submitForm(data, callback) {
            $.ajax({
                headers: requestHeaders(),
                url: `${BASE_URL2}/generalBusiness/generalSave`,
                type: 'POST',
                data,
                success: function (res) {
                    callback(res)
                },
                complete: function (XMLHttpRequest) {
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json"
            })
        },
        handleChange({ raw }) {//导入监听文件
            const that = this;
            var reader = new FileReader();
            reader.readAsBinaryString(raw);
            reader.onload = function (e) {
                var data = e.target.result;
                var wb = XLSX.read(data, {
                    type: 'binary' //以二进制的方式读取
                });
                var sheet = wb.Sheets[wb.SheetNames[0]];//sheet0代表excel表格中的第一页
                var json = XLSX.utils.sheet_to_json(sheet);//利用接口实现转换。
                //1.查询用户信息，并展示到页面上
                let sql1 = "";
                let specifications = [];
                json.forEach((item, index) => {
                    if (!specifications.some(i => i == (item['用户手机号'] + '').trim())) {
                        specifications.push((item['用户手机号'] + '').trim());
                        if (index == 0) {
                            sql1 = sql1 + "business_member_info.Member_SerialNumber='" + (item['用户手机号'] + '').trim() + "'\r\n"
                        } else {
                            sql1 = sql1 + " or business_member_info.Member_SerialNumber='" + (item['用户手机号'] + '').trim() + "'\r\n"
                        }
                    }
                })
                $.ajax({
                    headers: requestHeaders(),
                    type: 'POST',
                    url: `${BASE_URL2}/generalBusiness/generalQueryBySQLSerialNumber`,
                    data: {
                        SQLSerialNumber: 'A_business_member_info1',
                        Condition: '',
                        ExtensionCondition: window.btoa(unescape(encodeURIComponent(`and (${sql1})`))),
                    },
                    success: function (Result) {
                        let arr = [];
                        json.forEach(item => {
                            if (!Result.some(i => i.Member_SerialNumber == (item['用户手机号'] + '').trim())) {
                                arr.push({
                                    Member_SerialNumber: (item['用户手机号'] + '').trim(),
                                    Activity_SerialNumber: (item['活动内码'] + '').trim(),
                                    Points: (item['变动积分值'] + '').trim(),
                                    Notes: (item['备注'] + '').trim(),
                                    Points_Title: item['标题'] ? item['标题'] : (item['变动积分值'] > 0 ? '导入增加积分' : '导入扣减积分'),
                                    isError: true,
                                    isStatus: '2',
                                    Cause: '未查询到对应用户',
                                })
                            } else if (!that.Activity.some(i => i.Activity_SerialNumber == (item['活动内码'] + '').trim())) {
                                arr.push({
                                    Member_SerialNumber: (item['用户手机号'] + '').trim(),
                                    Activity_SerialNumber: (item['活动内码'] + '').trim(),
                                    Points: (item['变动积分值'] + '').trim(),
                                    Notes: (item['备注'] + '').trim(),
                                    Points_Title: item['标题'] ? item['标题'] : (item['变动积分值'] > 0 ? '导入增加积分' : '导入扣减积分'),
                                    isError: true,
                                    isStatus: '2',
                                    Cause: '未查询到对应活动',
                                })
                            } else {
                                arr.push({
                                    ...Result.filter(i => i.Member_SerialNumber == (item['用户手机号'] + '').trim())[0],
                                    Activity_Name: that.Activity.filter(i => i.Activity_SerialNumber == (item['活动内码'] + '').trim())[0].Activity_Name,
                                    Member_SerialNumber: (item['用户手机号'] + '').trim(),
                                    Activity_SerialNumber: (item['活动内码'] + '').trim(),
                                    Points: (item['变动积分值'] + '').trim(),
                                    Notes: (item['备注'] + '').trim(),
                                    Points_Title: item['标题'] ? item['标题'] : (item['变动积分值'] > 0 ? '导入增加积分' : '导入扣减积分'),
                                    isEdit: false,
                                    isStatus: '0',
                                    Cause: '',
                                })
                            }
                        })
                        that.tableData = arr;
                    },
                    complete: function (XMLHttpRequest) {
                        requestPretreatment(XMLHttpRequest);
                    },
                    dataType: "json"
                });
            }
        },
        handleSizeChange(val) {
            this.form.page = 1;
            this.form.limit = val;
        },
        handleCurrentChange(val) {
            this.form.page = val;
        },
        handleEdit(row) {//修改当前行
            row.isEdit = !row.isEdit
        },
        handleRemove(index) {//移除当前行
            this.$confirm('是否要删除此行?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }).then(() => {
                this.tableData = this.tableData.filter((i, id) => id != (this.form.page - 1) * this.form.limit + index);
            }).catch(() => { });
        },
        handleClean() {//清空
            this.$confirm('是否要清空导入数据?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }).then(() => {
                this.tableData = []
            }).catch(() => { });
        },
    },
})